<template>
  <div>{{ countDown }}</div>
</template>

<script>
export default {
  data() {
    return {
      countDown: '',
      timer: null,
      endTime: 0
    }
  },
  mounted() {
    // 设置倒计时结束时间
    this.endTime = Date.now() + 180000; // 倒计时1分钟

    // 开始倒计时
    this.startCountDown();
  },
  methods: {
    startCountDown() {
      this.timer = setInterval(() => {
        const now = Date.now();
        const distance = this.endTime - now;

        // 倒计时结束
        if (distance <= 0) {
          clearInterval(this.timer);
          this.countDown = '00:00:00';
          return;
        }

        // 格式化倒计时时间
        this.countDown = this.formatCountDown(distance);
      }, 1000);
    },
    formatCountDown(distance) {
      // 计算小时、分钟、秒数
      const hours = Math.floor((distance / (1000 * 60 * 60)) % 24);
      const minutes = Math.floor((distance / 1000 / 60) % 60);
      const seconds = Math.floor((distance / 1000) % 60);

      // 拼接为 HH:mm:ss 格式
      const hh = hours < 10 ? '0' + hours : hours;
      const mm = minutes < 10 ? '0' + minutes : minutes;
      const ss = seconds < 10 ? '0' + seconds : seconds;

      return hh + ':' + mm + ':' + ss;
    }
  },
  beforeDestroy() {
    // 销毁时清除定时器
    clearInterval(this.timer);
  }
}
</script>